package com.lswms.job;

import com.lswms.common.utils.HttpClientUtils;
import com.lswms.common.utils.LotteryMoney;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dto.YnLotteryDTO;
import com.lswms.dto.YnLotteryRecordDTO;
import com.lswms.dto.YnPayRecordDTO;
import com.lswms.dto.YnSignDTO;
import com.lswms.dto.YnUserDTO;
import com.lswms.entity.YnLotteryEntity;
import com.lswms.entity.YnLotteryRecordEntity;
import com.lswms.entity.YnPayRecordEntity;
import com.lswms.entity.YnSignEntity;
import com.lswms.entity.YnSignRecordEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.service.YnLotteryRecordService;
import com.lswms.service.YnLotteryService;
import com.lswms.service.YnPayRecordService;
import com.lswms.service.YnSignRecordService;
import com.lswms.service.YnSignService;
import com.lswms.service.YnUserService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;



/**
 * 
 * @author Administrator
 *
 */
@Component
@Slf4j
public class SignTasks {

	@Autowired
	private YnSignService ynSignService;
	
	@Autowired
	private YnLotteryService ynLotteryService;
	
	@Autowired
	private YnLotteryRecordService ynLotteryRecordService;
	
	@Autowired
	private YnPayRecordService ynPayRecordService;
	
	@Autowired
	private YnUserService ynUserService;
	
	@Autowired
	private YnSignRecordService ynSignRecordService;

    /**
     * 每天凌晨0点添加新一期的挑战期数、抽奖信息
     */
    @Scheduled(cron="5 0 0 * * ? ")
    public void createSign(){
    	log.info("开始每天凌晨0点添加新一期的挑战期数、抽奖信息***");
        //添加新一期的挑战期数
    	String date = ZqDateUtil.MM_dd(ZqDateUtil.getNow());
    	String yyyy_MM_dd = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.getNow());
    	String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
    	
    	//打卡日期（第二天）
    	String signTime = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.addDate(ZqDateUtil.getNow(), 1, Calendar.DAY_OF_MONTH));
    	
        log.info("添加新一期的挑战期数:{}",date);
        for(int i = 1;i<=4;i++){
        	YnSignEntity dto = new YnSignEntity();
            dto.setSignNo(yyyyMMdd);
            dto.setNoDesc(yyyyMMdd);
            if(i == 1){
                dto.setSignName("Pemula");
                dto.setType("1");
                dto.setAmount(new BigDecimal(2500));
            }else if(i == 2){
                dto.setSignName("utama");
                dto.setType("2");
                dto.setAmount(new BigDecimal(5000));
            }else if(i == 3){
                dto.setSignName("menengah");
                dto.setType("3");
                dto.setAmount(new BigDecimal(10000));
            }else if(i == 4){
                dto.setSignName("Tingkat Lanjut");
                dto.setType("4");
                dto.setAmount(new BigDecimal(20000));
            }
            dto.setEnterTime(yyyy_MM_dd+" 00:00:00#"+yyyy_MM_dd+" 23:59:59");
            dto.setSignTime(signTime+" 05:00:00#"+signTime+" 07:59:59");
            dto.setCreateDate(ZqDateUtil.getNow());
            log.info("添加新一期的挑战期数dto:{}",dto);
            ynSignService.createSign(dto);
        }
        //添加抽奖信息
        YnLotteryEntity entity = new YnLotteryEntity();
        entity.setSignNo(yyyyMMdd);
        entity.setNoDesc(yyyyMMdd);
        entity.setSignName("第"+yyyyMMdd+"期-抽奖");
        entity.setLotteryCount(0);
        entity.setLotteryTime(yyyy_MM_dd+" 05:00:00#"+yyyy_MM_dd+" 23:59:59");
        entity.setCreateDate(ZqDateUtil.getNow());
        ynLotteryService.createLottery(entity);
        log.info("结束每天凌晨0点添加新一期的挑战期数、抽奖信息***");
    }
    
    /**
     * 每天凌晨00:01更新上一期抽奖奖池
     */
    @Scheduled(cron="0 1 0 * * ?")
    public void updateLotteryAmount(){
    	log.info("开始每天凌晨00:01更新上一期抽奖奖池***");
    	//上一期
    	String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -1, Calendar.DAY_OF_MONTH));
    	log.info("上一期期数:{}",yyyyMMdd);
		//查询期数列表
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("signNo", yyyyMMdd);
		List<YnSignDTO> sign = ynSignService.list(map);
		//总提现金额手续费
		BigDecimal cashFee = BigDecimal.ZERO;
		for(YnSignDTO dto : sign){
			cashFee = cashFee.add(dto.getCashoutAmount());
		}
		//免费抽奖的奖金来源为当天派奖金额提现费用的20%
		BigDecimal lotteryAmount = cashFee.multiply(new BigDecimal(0.2));
		//更新上一期抽奖金额
		List<YnLotteryDTO> list = ynLotteryService.list(map);
		YnLotteryDTO dto = new YnLotteryDTO();
		if(list.size() > 0){
			dto = list.get(0);
		}
		YnLotteryEntity lotteryCount = new YnLotteryEntity();
		lotteryCount.setLotteryAmount(lotteryAmount);
		lotteryCount.setId(dto.getId());
		lotteryCount.setUpdateDate(ZqDateUtil.getNow());
		ynLotteryService.updateById(lotteryCount);
		log.info("结束每天凌晨00:01更新上一期抽奖奖池***");
    }
    
    /**
     * 每天10点开上一期抽奖结果
     */
    @Scheduled(cron="0 0 10 * * ?")
    public void updateSignLotteryAmount(){
    	log.info("开始每天10点开上一期抽奖结果***");
    	//上一期
    	String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -1, Calendar.DAY_OF_MONTH));
    	//查询上一期抽奖记录
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("signNo", yyyyMMdd);
    	List<YnLotteryRecordDTO> list = ynLotteryRecordService.list(map);
    	//没人参与抽奖
    	if(list.size() <= 0){
    		return;
    	}
    	//查询上期奖金
		List<YnLotteryDTO> lottery = ynLotteryService.list(map);
		YnLotteryDTO dto = new YnLotteryDTO();
		if(lottery.size() > 0){
			dto = lottery.get(0);
		}
		//查询上一期挑战人数（同一个人参加多个场次只算一次）
    	List<YnSignRecordEntity> listSign = ynSignRecordService.queryUserSign(yyyyMMdd, null, null, null);
    	Map<String,String> users = new HashMap<String,String>();
    	for(YnSignRecordEntity rec : listSign){
    		if(users.get(rec.getUserId()+"") == null){
    			users.put(rec.getUserId()+"", rec.getUserId()+"");
    		}
    	}
    	//参与人数50%
		BigDecimal totalNum = new BigDecimal(users.size()).multiply(new BigDecimal(0.5));
    	String userNum = MoneyUtil.bigDecimal2String(totalNum, 0);
    	log.info("每天10点开上一期抽奖:总人数：{}，总人数50%:{}，抽奖人数:{}",users.size(),totalNum+"--"+userNum,list.size());
		//随机1、2、3等奖
		List<YnLotteryRecordDTO> newList = queryRandom(list,3);
		log.info("每天10点开上一期抽奖，随机1、2、3等奖:{}",JSON.toJSONString(newList));
		Long userId1 = null,userId2 = null,userId3 = null;
		//总奖金
		BigDecimal lotteryAmount = dto.getLotteryAmount();
		//奖金分配（1等奖15%，2等奖10%，3等奖5%，剩余70%平分给所有抽奖用户）
		BigDecimal amount1 = BigDecimal.ZERO;
		BigDecimal amount2 = BigDecimal.ZERO;
		BigDecimal amount3 = BigDecimal.ZERO;
		if(newList.size() == 1){
			userId1 = newList.get(0).getUserId();
			amount1 = lotteryAmount.multiply(new BigDecimal(0.15));
		}else if(newList.size() == 2){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			amount1 = lotteryAmount.multiply(new BigDecimal(0.15));
			amount2 = lotteryAmount.multiply(new BigDecimal(0.10));
		}else if(newList.size() == 3){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId3 = newList.get(2).getUserId();
			amount1 = lotteryAmount.multiply(new BigDecimal(0.15));
			amount2 = lotteryAmount.multiply(new BigDecimal(0.10));
			amount3 = lotteryAmount.multiply(new BigDecimal(0.05));
		}
		log.info("每天10点开上一期抽奖，奖池:{},1-:{},2-:{},3-:{}",lotteryAmount,amount1,amount2,amount3);
		//如抽奖人数<参与人数50%则不开1等级
    	if(list.size() < Integer.parseInt(userNum)){
    		lotteryAmount = lotteryAmount.subtract(amount1);
    		amount1 = BigDecimal.ZERO;
    	}

		BigDecimal balance = lotteryAmount.subtract(amount3).subtract(amount2).subtract(amount1);

		//先平分剩余金额
		//List<BigDecimal> amount = LotteryMoney.randomHandOutAlgorithm(new BigDecimal(200), 5, 2, new BigDecimal(0.01));
		BigDecimal pf = balance.divide(new BigDecimal(list.size()), 5,BigDecimal.ROUND_DOWN);
		log.info("每天10点开上一期抽奖，除去123等奖后金额:{},pf：{}",balance,pf);
		for(int i = 0;i<list.size();i++){
			YnLotteryRecordDTO record = list.get(i);
			//更新中奖记录
			YnLotteryRecordEntity entity = new YnLotteryRecordEntity();
			entity.setId(record.getId());
			//1等奖
			if(record.getUserId() == userId1){
				pf = pf.add(amount1);
				entity.setLotteryLevel("1");
			//2等奖
			}else if(record.getUserId() == userId2){
				pf = pf.add(amount2);
				entity.setLotteryLevel("2");
			//3等奖
			}else if(record.getUserId() == userId3){
				pf = pf.add(amount3);
				entity.setLotteryLevel("3");
			}else{
				entity.setLotteryLevel("4");
			}
			entity.setAmount(pf);
			entity.setUpdateDate(ZqDateUtil.getNow());
			log.info("每天10点开上一期抽奖，更新用户中奖金额:{}",JSON.toJSONString(entity));
			ynLotteryRecordService.updateById(entity);
			//添加交易记录
			ynPayRecordService.payrecord(record.getUserId(),Long.parseLong(record.getSignNo()),"LOTTERY","bank",pf,"抽奖");
			//修改用户余额
			YnUserDTO userDto = ynUserService.get(record.getUserId());
			BigDecimal total = userDto.getBalance().add(pf);
			YnUserEntity userEntity = new YnUserEntity();
			userEntity.setBalance(total);
			userEntity.setId(userDto.getId());
			userEntity.setUpdateDate(ZqDateUtil.getNow());
			log.info("每天10点开上一期抽奖，更新用户余额:{}",JSON.toJSONString(userEntity));
			ynUserService.updateById(userEntity);			
		}
		log.info("结束每天10点开上一期抽奖结果***");
    }
    //生成不重复的1、2、3等奖（抽奖）
    public List<YnLotteryRecordDTO> queryRandom(List<YnLotteryRecordDTO> list,int count){
		List<YnLotteryRecordDTO> newList = new ArrayList<YnLotteryRecordDTO>();
        if(list.size() <= count){
        	newList = list;
        }else{
            Random random=new Random();
            List<Integer> tempList=new ArrayList<Integer>();
            int temp=0;
            for(int i=0;i<count;i++){
                temp=random.nextInt(list.size());
                if(!tempList.contains(temp)){
                    tempList.add(temp);
                    newList.add(list.get(temp));
                }
                else{
                    i--;
                }   
            }
        }
        return newList;
    }
    //生成不重复的1、2、3等奖（打卡）
    public List<YnSignRecordEntity> queryRandomSign(List<YnSignRecordEntity> list,int count){
		List<YnSignRecordEntity> newList = new ArrayList<YnSignRecordEntity>();
        if(list.size() <= count){
        	newList = list;
        }else{
            Random random=new Random();
            List<Integer> tempList=new ArrayList<Integer>();
            int temp=0;
            for(int i=0;i<count;i++){
                temp=random.nextInt(list.size());
                if(!tempList.contains(temp)){
                    tempList.add(temp);
                    newList.add(list.get(temp));
                }
                else{
                    i--;
                }   
            }
        }
        return newList;
    }
    /**
     * 每天8点开上一期打卡结果
     */
    @Scheduled(cron="0 0 8 * * ?")
    public void updateSignAmount(){
    	log.info("开始每天8点开上一期打卡结果***");
    	//上一期
    	String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -1, Calendar.DAY_OF_MONTH));
    	//处理每个等级的打卡记录
    	setSignResult(yyyyMMdd,"1");
    	setSignResult(yyyyMMdd,"2");
    	setSignResult(yyyyMMdd,"3");
    	setSignResult(yyyyMMdd,"4");
    	
		log.info("结束每天8点开上一期打卡结果***");
    }
    
    /**
     * 打卡奖金
     */
    public void setSignResult(String yyyyMMdd,String type){
    	//查询上一期挑战记录
    	List<YnSignRecordEntity> list = ynSignRecordService.queryUserSign(yyyyMMdd, type, null, null);
    	//期数信息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("signNo", yyyyMMdd);
		map.put("type", type);
    	List<YnSignDTO> signList = ynSignService.list(map);
    	YnSignDTO signDtto = signList.get(0);
    	//没人参与挑战或者打卡
    	if(list.size() <= 0){
    		return;
    	}
		//打卡人列表
		List<YnSignRecordEntity> listDk = new ArrayList<YnSignRecordEntity>();
    	//打卡人数
    	int signNum = 0;
    	for(YnSignRecordEntity rec : list){
    		if(rec.getSignTime() != null){
    			signNum ++ ;
    			listDk.add(rec);
    		}else{
    	    	//更新未打卡的，挑战失败
    			YnSignRecordEntity re = new YnSignRecordEntity();
    			re.setId(rec.getId());
    			re.setStatus("2");
    			re.setUpdateDate(ZqDateUtil.getNow());
    			ynSignRecordService.updateById(re);
    		}
    	}
    	log.info("每天8点打卡奖金，参与人数:{}，打卡人数:{}",list.size(),signNum);
    	//没人打卡退还50%报名费
    	if(signNum == 0){
    		for(YnSignRecordEntity rec : list){
    			BigDecimal back = signDtto.getAmount().multiply(new BigDecimal(0.5));
    			//添加交易记录
    			ynPayRecordService.payrecord(rec.getUserId(),Long.parseLong(signDtto.getSignNo()),"BACK","bank",back,"退还");
    			//修改用户余额
    			YnUserDTO userDto = ynUserService.get(rec.getUserId());
    			BigDecimal total = userDto.getBalance().add(back);
    			YnUserEntity userEntity = new YnUserEntity();
    			userEntity.setBalance(total);
    			userEntity.setId(userDto.getId());
    			userEntity.setUpdateDate(ZqDateUtil.getNow());
    			log.info("每天8点打卡奖金，没人打卡退还50%报名费:{}",JSON.toJSONString(userEntity));
    			ynUserService.updateById(userEntity);			
    		}
    		return;
    	}
		//随机1、2、3等奖
		Long userId1 = null,userId2 = null,userId22 = null,userId3 = null,userId33 = null,userId333 = null,userId3333 = null,userId33333 = null,userId333333 = null;
		List<YnSignRecordEntity> newList = queryRandomSign(listDk,9);
		if(newList.size() == 1){
			userId1 = newList.get(0).getUserId();
		}else if(newList.size() == 2){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
		}else if(newList.size() == 3){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
		}else if(newList.size() == 4){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
		}else if(newList.size() == 5){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
			userId33 = newList.get(4).getUserId();
		}else if(newList.size() == 6){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
			userId33 = newList.get(4).getUserId();
			userId333 = newList.get(5).getUserId();
		}else if(newList.size() == 7){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
			userId33 = newList.get(4).getUserId();
			userId333 = newList.get(5).getUserId();
			userId3333 = newList.get(6).getUserId();
		}else if(newList.size() == 8){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
			userId33 = newList.get(4).getUserId();
			userId333 = newList.get(5).getUserId();
			userId3333 = newList.get(6).getUserId();
			userId33333 = newList.get(7).getUserId();
		}else if(newList.size() == 9){
			userId1 = newList.get(0).getUserId();
			userId2 = newList.get(1).getUserId();
			userId22 = newList.get(2).getUserId();
			userId3 = newList.get(3).getUserId();
			userId33 = newList.get(4).getUserId();
			userId333 = newList.get(5).getUserId();
			userId3333 = newList.get(6).getUserId();
			userId33333 = newList.get(7).getUserId();
			userId333333 = newList.get(8).getUserId();
		}
		log.info("每天8点打卡奖金，随机1、2、3等奖:{}",JSON.toJSONString(newList));
		//总金额（分派金额+上期剩余金额）
		BigDecimal totalAmount = signDtto.getDistributeAmount().add(signDtto.getLastAmount());
		//奖金设置：一等奖派奖奖金的8%*1，二等奖派奖奖金的3%*2，三等奖派奖奖金的1%*6；剩余80%的奖金随机分配给（除123等奖）打卡成功的用户
		BigDecimal amount1 = totalAmount.multiply(new BigDecimal(0.08));
		BigDecimal amount2 = totalAmount.multiply(new BigDecimal(0.03));
		BigDecimal amount3 = totalAmount.multiply(new BigDecimal(0.01));
		log.info("每天8点打卡奖金，总金额:{},1-:{},2-:{},3-:{}",totalAmount,amount1,amount2,amount3);
		//1、2、3等奖已经发了多少
		BigDecimal yfAmount = BigDecimal.ZERO;
		//1、2、3等奖共多少人
		int count123 = 0;
		//除去1、2、3等奖用户后的列表
		List<YnSignRecordEntity> listDk1 = new ArrayList<YnSignRecordEntity>();
		//发123等奖
		for(int i = 0;i<listDk.size();i++){
			YnSignRecordEntity record = listDk.get(i);
			YnSignRecordEntity updateRec = new YnSignRecordEntity();
			updateRec.setId(record.getId());
			updateRec.setUpdateDate(ZqDateUtil.getNow());
			//1等奖
			if(record.getUserId() == userId1){
				count123 ++ ;
				yfAmount = yfAmount.add(amount1);
				updateRec.setAmount(amount1);
				updateRec.setSignLevel("1");
				ynSignRecordService.updateById(updateRec);
				createPayRecord(record.getUserId(),Long.parseLong(record.getSignNo()),amount1);
			//2等奖
			}else if(record.getUserId() == userId2 || record.getUserId() == userId22){
				count123 ++ ;
				yfAmount = yfAmount.add(amount2);
				updateRec.setAmount(amount2);
				updateRec.setSignLevel("2");
				ynSignRecordService.updateById(updateRec);
				createPayRecord(record.getUserId(),Long.parseLong(record.getSignNo()),amount2);

			//3等奖
			}else if(record.getUserId() == userId3 || record.getUserId() == userId33 || record.getUserId() == userId333
					 || record.getUserId() == userId3333 || record.getUserId() == userId33333 || record.getUserId() == userId333333){
				count123 ++ ;
				yfAmount = yfAmount.add(amount3);
				updateRec.setAmount(amount3);
				updateRec.setSignLevel("3");
				ynSignRecordService.updateById(updateRec);
				createPayRecord(record.getUserId(),Long.parseLong(record.getSignNo()),amount3);

			}else{
				listDk1.add(record);
			}
		}
		log.info("每天8点打卡奖金，123等奖已发金额:{},123等奖已发人数:{}",yfAmount,count123);
    	//有人打卡，计算参与人数的60%
		//总名额（总名额是报名数量的60%）
		BigDecimal total = new BigDecimal(list.size()).multiply(new BigDecimal(0.6));
		//四舍五入
		String userNum = MoneyUtil.bigDecimal2String(total, 0);
		//剩余80%的奖金随机分配给（除123等奖）打卡成功的用户
		BigDecimal balanceAmount = totalAmount.subtract(yfAmount);
		List<BigDecimal> moneyList = LotteryMoney.randomHandOutAlgorithm(balanceAmount,Integer.parseInt(userNum) - count123, 2, new BigDecimal(1));

		log.info("每天8点打卡奖金，剩余奖金随机分配给（除123等奖）打卡成功的用户:{}",balanceAmount);
		log.info("每天8点打卡奖金，总人数60%:{},剩余发送名额(除123等奖):{}",userNum,Integer.parseInt(userNum) - count123);
		log.info("每天8点打卡奖金，实际发放名额:{}",listDk1.size());
		//1、2、3等奖外的用户中奖金额
		BigDecimal zzAmount = BigDecimal.ZERO;
		//发剩余用户奖金（除去1、2、3等奖）
		for(int i = 0;i<listDk1.size();i++){
			zzAmount = zzAmount.add(moneyList.get(i));
			YnSignRecordEntity record = listDk1.get(i);
			YnSignRecordEntity updateRec = new YnSignRecordEntity();
			updateRec.setId(record.getId());
			updateRec.setUpdateDate(ZqDateUtil.getNow());
			updateRec.setAmount(moneyList.get(i));
			updateRec.setSignLevel("4");
			ynSignRecordService.updateById(updateRec);
			createPayRecord(record.getUserId(),Long.parseLong(record.getSignNo()),moneyList.get(i));
		}
		
		//剩余金额
		BigDecimal zzBalance = balanceAmount.subtract(zzAmount);
		String nowSign = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
    	//期数信息
		Map<String,Object> map1 = new HashMap<String,Object>();
		map1.put("signNo", nowSign);
		map1.put("type", type);
    	List<YnSignDTO> signList1 = ynSignService.list(map1);
    	YnSignDTO signDtto1 = signList1.get(0);

    	//更新剩余金额到当前期
    	YnSignEntity entity = new YnSignEntity();
    	entity.setId(signDtto1.getId());
    	entity.setLastAmount(zzBalance);
    	entity.setUpdateDate(ZqDateUtil.getNow());
    	log.info("每天8点打卡奖金，更新剩余金额到当前期:{}",JSON.toJSONString(entity));
    	ynSignService.updateById(entity);
    }
    //添加交易记录、修改账户余额
    public void createPayRecord(Long userId,Long signNo,BigDecimal amount){
		//添加交易记录
		ynPayRecordService.payrecord(userId,signNo,"SIGN","bank",amount,"打卡");
		//修改用户余额
		YnUserDTO userDto = ynUserService.get(userId);
		BigDecimal total = userDto.getBalance().add(amount);
		YnUserEntity userEntity = new YnUserEntity();
		userEntity.setBalance(total);
		userEntity.setId(userDto.getId());
		userEntity.setUpdateDate(ZqDateUtil.getNow());
		ynUserService.updateById(userEntity);			
    }
    
    //解冻，修改交易记录、修改账户余额
    public void jdCashOut(Long userId,Long payId,BigDecimal amount){
		//修改交易状态
		YnPayRecordEntity payRecord = new YnPayRecordEntity();
		payRecord.setId(payId);
		payRecord.setStatus(2);
		payRecord.setUpdateDate(ZqDateUtil.getNow());
		ynPayRecordService.updateById(payRecord);
		//加余额
		//修改用户余额
		YnUserDTO userDto = ynUserService.get(userId);
		BigDecimal total = userDto.getBalance().add(amount);
		YnUserEntity userEntity = new YnUserEntity();
		userEntity.setBalance(total);
		userEntity.setId(userDto.getId());
		userEntity.setUpdateDate(ZqDateUtil.getNow());
		ynUserService.updateById(userEntity);			
    }

    /**
     * 每天凌晨0点0分30秒（处理冻结的提现）
     */
    @Scheduled(cron="30 0 0 * * ? ")
    public void jobCashOut(){
    	log.info("开始 每天凌晨0点0分30秒（处理冻结的提现）***");
    	
    	String signTime = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.addDate(ZqDateUtil.getNow(), -1, Calendar.DAY_OF_MONTH));
    	
		Map<String,Object> map1 = new HashMap<String,Object>();
		map1.put("businessType", "CASHOUT");
		map1.put("status", 0);
		map1.put("d1", signTime+" 00:00:00");
		map1.put("d2", signTime+" 23:59:59");
		List<YnPayRecordDTO> rec = ynPayRecordService.list(map1);
		for(YnPayRecordDTO record : rec){
			String tradNo = record.getUuid();
            JSONObject retJson = HttpClientUtils.httpGet("http://149.129.235.68:29918/pay/api/out/getPayStatus?appKey=54fff46929fb49de8ed298e2026ec444&transactionId="+tradNo);
            log.info("查询支付状态结果：{}",JSON.toJSONString(retJson));
            
            if(retJson != null && retJson.getIntValue("code") == 200 
            		&& "SUCCESS".equals(retJson.getString("message"))) {
            	
            	JSONObject retJson1 = (JSONObject)retJson.get("result");
            	if(retJson1 != null){
                	String uuid = retJson1.getString("transactionId");
                	String payStatus = retJson1.getString("payStatus");
                	int payMoney = retJson1.getIntValue("payMoney");
                	if("SUCCESS".equals(payStatus) && uuid.equals(tradNo) 
                			&& record.getAmt().compareTo(new BigDecimal(payMoney)) == 0){
            			//修改交易状态
                		YnPayRecordEntity payRecord = new YnPayRecordEntity();
                		payRecord.setId(record.getId());
                		payRecord.setStatus(1);
                		payRecord.setUpdateDate(ZqDateUtil.getNow());
            			ynPayRecordService.updateById(payRecord);
                	}else{
                		jdCashOut(record.getUserId(),record.getId(),record.getAmt());
                	}
            	}else{
                	jdCashOut(record.getUserId(),record.getId(),record.getAmt());
                }
            }
		}
        log.info("结束 每天凌晨0点0分30秒（处理冻结的提现）***");
    }

}
